<template>
    <div class="full-percent">
        <div style="display: flex;">
            <div style="width: 150px;text-align: right;padding-right: 10px;line-height: 32px;">
                Writer择数据库
            </div>
            <div style="padding-right: 5px;width: calc((80% - 400px)/2);">
                <el-select v-model="etlConfig.dbType" placeholder="请选择数据库" @change="clearDB" class="input-auto-resize">
                    <el-option v-for="item in dbTypes" :key="item" :label="item" :value="item" />
                </el-select>
            </div>
            <div style="padding-right: 5px;width: calc((80% -  400px)/2);">
                <el-select v-model="etlConfig.dbSequence" placeholder="请选择实例" class="input-auto-resize"
                    @change="clearTable">
                    <el-option v-for="(item, index) in dbNames" :key="index" :label="item.name" :value="item.sequence"
                        :disabled="readerDb === item.sequence" />
                </el-select>
            </div>
            <div style="width: 120px;text-align: right;padding-right: 10px;line-height: 32px;">
                Writer匹配表名
            </div>
            <el-input v-model="etlConfig.table" class="font-auto-resize" style="width: 20%;"
                placeholder="为空查询所有有权限的表" />
            <div style="width: 50px;text-align: right;">
                <el-button :icon="getIcon('search')" class="button-auto-resize" @click="searchTable" circle
                    :disabled="!etlConfig.dbSequence" type="primary" />
            </div>
        </div>

        <div class="tables">
            <div v-waterfall="350" v-if="Object.keys(tables).length">
                <div v-for="item in Object.keys(etlConfig.tableMapping)" class="item"
                    :style="`box-shadow: 0 0 0 1px ${etlConfig.tableMapping[item] ? 'rgba(0, 0, 0, 0.1)' : '#bf0d0d73'} inset;`">
                    <div class="item-inner">
                        <div style="display: flex;height: 32px;align-items: center;">
                            <div style="padding-right: 10px;width: 60px;">表输入</div>
                            <tooltip :modelValue="item" border style="width: calc(100% - 70px)!important;" />
                        </div>
                        <div style="display: flex;height: 32px;align-items: center;padding-top: 5px;">
                            <div style="padding-right: 10px;width: 60px;">表输出</div>
                            <tooltip :modelValue="etlConfig.tableMapping[item]" border
                                style="width: calc(100% - 70px)!important;" placeholder="配置表输出">
                                <template #suffix>
                                    <el-icon class="el-input__icon" @click="setTableOut(item)">
                                        <component :is="getIcon('DArrowRight')" />
                                    </el-icon>
                                </template>
                            </tooltip>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else class="unselectTable">
                请选择数据库连接信息以配置表映射关系
            </div>
        </div>

        <el-drawer :show-close="false" :with-header="false" size="900px" v-model="showDrawer" direction="rtl"
            class="table-drawer forbid-select" @open="open" @closed="close" append-to-body>
            <el-tabs v-model="activeTab" type="border-card" ref="tabRef" class="table-tab"
                v-if="Object.keys(tables).length">
                <el-tab-pane :label="item" :name="`schema_${index}`" v-for="(item, index) in Object.keys(tables)"
                    :key="index">
                    <el-scrollbar class="full-percent">
                        <div v-waterfall>
                            <div v-for="(tableItem, tableItemindex) in tables[item]" :key="tableItemindex"
                                class="table-item" @click="selectTable(tableItem)">
                                {{ tableItem.table_name }}
                            </div>
                        </div>
                    </el-scrollbar>
                </el-tab-pane>
            </el-tabs>
        </el-drawer>
    </div>
</template>

<script setup>
import { useRequest, useModalSize } from "@usehook"
import { getIcon } from "@/utils/tools"

const props = defineProps({
    db: {
        type: Object,
        required: true,
        default: {}
    },
    dbTypes: {
        type: Array,
        required: true,
        default: []
    },
    readerTable: {
        type: Array,
        required: true,
        default: []
    },
    readerDb: {
        type: [Number, String],
        required: false,
        default: ""
    }
})

let etlConfig = $ref({ tableMapping: {} })
let dbNames = $ref([])
let tables = $ref([])
let showDrawer = $ref(false)
let currentTableIn = $ref("")
let activeTab = $ref("")
const emit = defineEmits(['change'])

const setTableOut = (item) => {
    showDrawer = true
    currentTableIn = item
}

const searchTable = () => {
    if (!etlConfig.dbSequence) return
    useRequest({ url: "/data/table/search", loadingMessage: "正在查询数据库获取表信息", loadingTarget: ".console-page", dbSequence: etlConfig.dbSequence, table: etlConfig.table }).then(resp => {
        if (resp && resp.status) {
            tables = resp.data.reduce((acc, item) => {
                const schema = item.table_schema;
                (acc[schema] || (acc[schema] = [])).push(item); // 按 schema 分组
                return acc
            }, {});
        }
    })
}

const clearDB = () => {
    etlConfig.dbSequence = ""
    clearTable()
}

const clearTable = (sequence) => {
    tables = []
    for (let t of Object.keys(etlConfig.tableMapping)) {
        etlConfig.tableMapping[t] = ""
    }
    etlConfig.dbName = Object.values(props.db).flatMap(e => e).filter(e => e.sequence === sequence)[0]?.name
}

const open = () => {
    activeTab = "schema_0"
    useModalSize()
}

const close = () => {
    useModalSize(false)
}

const selectTable = (table) => {
    etlConfig.tableMapping[currentTableIn] = table.table_schema + "." + table.table_name
    showDrawer = false
}

watchEffect(() => {
    dbNames = props.db[etlConfig.dbType]
})

watch(() => props.readerTable, readerTable => {
    etlConfig.tableMapping = readerTable.reduce((acc, key) => {
        acc[key] = etlConfig.tableMapping[key] || ""
        return acc;
    }, {});
}, { immediate: true, deep: true })

watch(() => etlConfig, (config) => {
    emit("change", config)
}, { deep: true })
</script>

<style>
.item {
    width: 350px;
    background: #ebebeb42;
    border-radius: 3px;
}

.item .item-inner {
    padding: 10px 15px;
}

.table-drawer .table-item {
    padding: 5px 10px;
    height: 40px;
    line-height: 40px;
    background: rgb(169 169 169 / 18%);
    border-radius: 3px;
}

.table-drawer .el-tab-pane {
    height: calc(100% - 10px) !important;
    padding: 5px;
}
</style>